
using Godot;
using System;
using Newtonsoft.Json;
using System.ComponentModel;

public partial class rotation : Node3D
{
	[Signal]
	public delegate void SignalUpdateSendRobotParametersEventHandler(string robotParameters);

	public double currentAngle { get; set; }

	public double deltaAngle { get; set; }

	public double tempAngle { get; set; }

	public RobotJoints robotJoints { get; set; }

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		var mainNode = this.Owner.Owner;//获取main节点
		robotJoints = new RobotJoints();
		currentAngle = 0.0d;
		tempAngle = 0.0d;
		deltaAngle = 0.0d;
		mainNode.Connect("SignalSendRobotParameters", new Callable(this, "RecieveData"));//连接信号
		SignalUpdateSendRobotParameters += UpdateSendRobotParameters;
	}

	/// <summary>
	/// 更新机械臂信息
	/// </summary>
	/// <param name="robotParameters">更新机械臂数据信息</param>
	/// <exception cref="NotImplementedException"></exception>
	private void UpdateSendRobotParameters(string robotParameters)
	{
	}

	/// <summary>
	/// 接收信息
	/// </summary>
	/// <param name="data">接收到的信息</param>
	public void RecieveData(string data)
	{
		robotJoints = JsonConvert.DeserializeObject<RobotJoints>(data);//解析关节信号
		currentAngle = (double)robotJoints.GetType().GetProperty($"{Name}Angle").GetValue(robotJoints);
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
		//var isActivated = (bool)robotJoints.GetType().GetProperty($"{this.Name}Activated").GetValue(robotJoints);
		if ( tempAngle!= currentAngle)//robotJoints.currentJoint == this.Name
		{
			deltaAngle = (currentAngle - tempAngle)/ 180 * Mathf.Pi;
			RotateObjectLocal(new Vector3(0, 0, 1), (float)deltaAngle);
			tempAngle = currentAngle;
			//currentAngle += deltaAngle;

			/*if (Input.IsActionPressed("ui_up"))
			{
				deltaAngle = 1.0f / 180 * Mathf.Pi;
				RotateObjectLocal(new Vector3(0, 0, 1), deltaAngle);
				currentAngle += deltaAngle;
			}
			if (Input.IsActionPressed("ui_down"))
			{
				deltaAngle = 1.0f / 180 * Mathf.Pi;
				RotateObjectLocal(new Vector3(0, 0, 1), -deltaAngle);
				currentAngle += -deltaAngle;
			}*/
			Transform3D transform = Transform;
			transform = transform.Orthonormalized();
			transform = transform.Scaled(new Vector3(1.0f, 1.0f, 1.0f));
			robotJoints.GetType().GetProperty($"{Name}Angle").SetValue(robotJoints, currentAngle * 180 / Mathf.Pi);
			EmitSignal(SignalName.SignalUpdateSendRobotParameters, JsonConvert.SerializeObject(robotJoints));
		}
	}
}
